package com.smc.sys.utils;



import java.util.List;
import java.util.Objects;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.smc.common.config.Global;
import com.smc.common.utils.CacheUtils;
import com.smc.common.utils.StringUtils;
import com.smc.sys.model.Menu;
import com.smc.sys.model.User;
import com.smc.sys.security.AppContext;
import com.smc.sys.security.Principal;

/**
 * 用户工具类
 * @author ThinkGem
 * @version 2013-12-05
 */
public class UserUtils {

    private static Logger logger = LoggerFactory.getLogger(UserUtils.class);
    
	/*private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
	private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
	private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);*/

    
    public static final String SYS_INDEX = Global.getAdminPath();
    public static final String LOGIN_SRC_LOCAL = "local";
    public static final String LOGIN_SRC_SSO = "sso";
    public static final String LOGIN_PATH = SYS_INDEX+"/login";
    
	public static final String USER_CACHE = "userCache";
	public static final String USER_CACHE_ID_ = "id_";
	public static final String USER_CACHE_TOKEN_ = "token_";
	public static final String USER_CACHE_LOGIN_NAME_ = "ln";
	public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_";

	public static final String CACHE_ROLE_LIST = "roleList";
	public static final String CACHE_MENU_LIST = "menuList";
	public static final String CACHE_AREA_LIST = "areaList";
	public static final String CACHE_OFFICE_LIST = "officeList";
	public static final String CACHE_OFFICE_ALL_LIST = "officeAllList";
	
	public static Boolean isSSOLogin(){
		Boolean flag = true;
		try {
			String loginSrc = SysUtils.getLoginSrc();
			if(LOGIN_SRC_LOCAL.equalsIgnoreCase(loginSrc)){
				flag = false;
			}
		} catch (Exception e) {
		    logger.error("isSSOLogin 异常 ",e);
		}
		
		return flag;
	}
	
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	/*public static User get(Integer id){
		User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
		//user = null;
		if (user ==  null){
			user = userDao.get(id);
			if (user == null){
				return null;
			}
			user.setRoleList(roleDao.findList(new Role(user)));
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}*/
	
	public static void CacheUser(User user){
		if(user!=null){
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
	}
	
	
	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return 取不到返回null
	 */
	/*public static User getByLoginName(String loginName){
		User user = null;// (User)CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName);
		if (user == null){
			user = userDao.getByLoginName(new User(null, loginName));
			if (user == null){
				return null;
			}
			user.setRoleList(roleDao.findList(new Role(user)));
			CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
			CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
		}
		return user;
	}*/
	
	/**
	 * 清除当前用户缓存
	 */
	public static void clearCache(){
		removeCache(CACHE_ROLE_LIST);
		removeCache(CACHE_MENU_LIST);
		removeCache(CACHE_AREA_LIST);
		removeCache(CACHE_OFFICE_LIST);
		removeCache(CACHE_OFFICE_ALL_LIST);
		UserUtils.clearCache(getUser());
	}
	
	/**
	 * 清除指定用户缓存
	 * @param user
	 */
	public static void clearCache(User user){
		CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName());
		CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getOldLoginName());
	
	}
	
	/**
	 * 获取当前用户
	 * @return 取不到返回 new User()
	 */
	public static User getUser(){
		User user = AppContext.getUser();
		if(user != null){
			return user;
		}
		// 如果没有登录，则返回实例化空的User对象。
		return new User();
	}

	public static User getUserForNull(){
		User user = getUser();
		if(user == null){
			user = new User();
		}
		if(user.getId()==null){
			user.setId(0L);
		}
		return user;
	}
	/**
	 * 获取当前用户角色列表
	 * @return
	 */
	/*public static List<Role> getRoleList(){
		@SuppressWarnings("unchecked")
		List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
		if (roleList == null){
			User user = getUser();
			if (user.isAdmin()){
				roleList = roleDao.findAllList(new Role());
			}else{
				Role role = new Role();
				role.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "u"));
				roleList = roleDao.findList(role);
			}
			putCache(CACHE_ROLE_LIST, roleList);
		}
		return roleList;
	}*/
	
	/**
	 * 获取当前用户授权菜单
	 * @return
	 */
	public static List<Menu> getMenuList(){
		List<Menu> menuList = null;
       
		
        try {
                menuList = MenuUtils.getAllMenuListByConfig();
		} catch (Exception e) {
			logger.error("获取菜单异常",e);
		}
		
		menuList = MenuUtils.getAllMenuListByConfig();
		List<Menu> menus = filterMenuList(menuList);
        return menus;
	}
	
	public static List<Menu> filterMenuList(List<Menu> list){
		List<Menu> menuList = Lists.newArrayList();
		if(CollectionUtils.isNotEmpty(list)){
			User user = UserUtils.getUser();
        	Boolean isAdmin = user.isAdmin();
        	Boolean isFileAdmin = user.isFileManager();
        	Boolean isHomeworkMember = user.isHomeworkMember();
        	Boolean isHomeworkAdmin = user.isHomeworkManager();
        	Boolean isCourseConfigManager = user.isCourseConfigManager();
        	List<String> roleCodeList = user.getRoleCodeList();
        	for (Menu menu : list) {
        		 String id = menu.getId()==null?"":menu.getId().toString();
                 if(isAdmin || isCourseConfigManager){ //admin管理员 可以看文件、课件，
                 	if(Lists.newArrayList("121","124","125").contains(id)){
                 		menu.setIsShow("1");
                 	}
                 	if(Lists.newArrayList("123","1233").contains(id)){
                 		menu.setIsShow("1");
                 	}
                 }
                 if(isFileAdmin){ //课上传和查看作业
                 	if(Lists.newArrayList("121","124").contains(id)){
                 		menu.setIsShow("1");
                 	}
                 	if(Lists.newArrayList("123","1233").contains(id)){
                 		menu.setIsShow("1");
                 	}
                 }
                 if(isHomeworkMember){ //组员课 不能发布，上传线上作业
                 	if(Lists.newArrayList("123","1231","1233").contains(id)){
                 		menu.setIsShow("1");
                 	}
                 }
                 if(isHomeworkAdmin){ //管理员 可以发布和上传线上作业
                 	if(Lists.newArrayList("123","1231","1233").contains(id)){
                 		menu.setIsShow("1");
                 	}
                 }
                 
                 if(isHomeworkAdmin && isFileAdmin){ //作业管理员和文件系统管理员可以上传线上作业
                 	if(Lists.newArrayList("1232").contains(id)){
                 		menu.setIsShow("1");
                 	}
                 }
                 
                 //隐藏原有上传
                 if(Lists.newArrayList("1231","1232","1233").contains(id)){
             		menu.setIsShow("0");
             	 }
                 if(!isCourseConfigManager){ //无权限关闭配置功能
                 	if(Lists.newArrayList("22","23").contains(id)){
                 		menu.setIsShow("0");
                 	}
                 }
                 if(Lists.newArrayList("24").contains(id)){ //题库菜单
                     if(roleCodeList.contains(User.STAFF_QBS_ADMIN) || roleCodeList.contains(User.STAFF_TAG_ADMIN) ){
                         menu.setIsShow("1");
                     }else{
                         menu.setIsShow("0");
                     }
                 }
                 if(!UserUtils.isSSOLogin()){ //
                     menu.setIsShow("1");
                 }
                 menu.setIsShow("1");//临时开启
                 menuList.add(menu);
			}
			
		}
		return menuList;
	}

	/**
	 * 获取授权主要对象
	 */
	public static Subject getSubject(){
		return SecurityUtils.getSubject();
	}
	
	/**
	 * 获取当前登录者对象
	 */
	public static Principal getPrincipal(){
		Principal principal = null;
		User user = null;
		String ssoToken = null;
		try{
			/*Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal)subject.getPrincipal();
			if (principal != null){
				return principal;
			}*/
			if(principal == null){
				user = AppContext.getUser();
				ssoToken = AppContext.getAppToken();
			}
			if(user!=null && user.getId()!=null && !Objects.equals(user.getId(), 0L)
			    && StringUtils.isNotBlank(ssoToken)){
				if(ssoToken == null){
					ssoToken = user.getToken();
				}
	        	principal = new Principal(user, false);
		        principal.setToken(ssoToken);
	        }
//			subject.logout();
		}catch (UnavailableSecurityManagerException e) {
		    logger.error("UnavailableSecurityManagerException 异常 ",e);
		}catch (InvalidSessionException e){
		    logger.error("InvalidSessionException 异常 ",e);
		}
		return principal;
	}
	
	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
//			subject.logout();
		}catch (InvalidSessionException e){
			
		}
		return null;
	}
	
	// ============== User Cache ==============
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
//		Object obj = getCacheMap().get(key);
		Object obj = getSession().getAttribute(key);
		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
//		getCacheMap().put(key, value);
		getSession().setAttribute(key, value);
	}

	public static void removeCache(String key) {
//		getCacheMap().remove(key);
		getSession().removeAttribute(key);
	}
	
//	public static Map<String, Object> getCacheMap(){
//		Principal principal = getPrincipal();
//		if(principal!=null){
//			return principal.getCacheMap();
//		}
//		return new HashMap<String, Object>();
//	}
	
}
